class BlogPost < ActiveRecord::Base
  
  cattr_reader    :per_page
  attr_protected  :body_html
  @@per_page = 10
  
  named_scope :recent, :limit => 3, :order => "created_at desc"
  named_scope :last_30_days, :conditions => "created_at > '#{30.days.ago.to_s(:db)}'", :order => "created_at desc"
  
  has_and_belongs_to_many   :tags, 
                            :join_table   => "tagged_items", 
                            :foreign_key  => "taggable_id", 
                            :conditions   => "taggable_type = '#{self.class_name}'", 
                            :insert_sql   => 'INSERT INTO tagged_items (taggable_id,tag_id,taggable_type) VALUES (#{id}, #{record.id}, \'#{self.class}\');',
                            :after_add    => :increment_tag_count, 
                            :after_remove => :decrement_tag_count

  belongs_to    :author, :class_name => 'User', :foreign_key => 'author_id'
  
  before_save   :update_stub_url, :if => Proc.new { |b| b.title_changed? }
  before_save   :markup_body, :if => Proc.new { |b| b.body_markdown_changed? }
  
  class << self
    def post_months
      BlogPost.find(:all, :select => "distinct date_format(created_at,'%M %Y') as label, date_format(created_at,'%m') as month_number, date_format(created_at,'%Y') as year_number", :order => "created_at desc")
    end
  end
  
  protected
  
  def increment_tag_count(tag)
    tag.count += 1
    tag.save
  end
  
  def decrement_tag_count(tag)
    # tag arrive at this method as readonly so I have to instantiate a new Tag object.  geh...
    t = Tag.find(tag.id)
    t.count -= 1
    t.save 
  end
  
  def update_stub_url
    self.stub_name = self.title.parameterize.to_s
  end
  
  def markup_body
    self.body_html = BlueCloth::new(self.body_markdown).to_html
  end
  
  
end
